// 权限管理中的角色列表的逻辑代码
export default {
  created() {
    this.getData();
  },
  data() {
    return {
      // 1 角色列表相关数据
      rolesList: [],
      // 2 添加角色相关数据
      addDialogFormVisible: false,
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      //添加和编辑公用的验证规则
      Rules: {
        roleName: [{ required: true, trigger: "blur", message: "角色名必填" }],
        roleDesc: [{ required: true, trigger: "blur", message: "角色描述必填" }]
      },
      //   3 编辑角色相关数据
      editDialogFormVisible: false,
      editForm: {
        roleName: "",
        roleDesc: "",
        id: ""
      },
    //   4 分配角色权限的相关数据
      rightDialogFormVisible:false,
      rightsTreeForm : [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      checkedIdArr:[],
      rightsRoleId:'',
    };
  },
  methods: {
    // 1获取角色列表的内容
    async getData() {
      const {
        data: { data, meta }
      } = await this.$http.get("roles");
      if (meta.status !== 200) return this.$message.error("获取角色失败");
      //   console.log(data);
      this.rolesList = data;
    },
    // 2点击添加按钮，显示对话框,重置数据
    openAddDialog() {
      this.addDialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.addFormRef.resetFields();
      });
    },
    // 3 点击确定进行角色的添加，校验表单
    addRoles() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const {
            data: { meta }
          } = await this.$http.post("/roles", this.addForm);
          if (meta.status !== 201) return this.$message.error("添加角色失败");

          this.$message.success("添加角色成功");
          this.getData();
          this.addDialogFormVisible = false;
        }
      });
    },
    // 4 点击删除按钮，进行角色的删除，携带id
    delRole(id) {
      this.$confirm("确定删除该用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const {
            data: { meta }
          } = await this.$http.delete(`roles/${id}`);
          // 失败情况
          if (meta.status !== 200) return this.$message.error("删除用户失败");
          // 成功情况
          this.getData();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 5 点击编辑按钮，显示对话框，重置数据，渲染数据
    openEditDialog(row) {
      // 此处也可以根据接口向后端发送请求，获取数据，
      this.editDialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.editFormRef.resetFields();
        this.editForm.roleName = row.roleName;
        this.editForm.roleDesc = row.roleDesc;
        this.editForm.id = row.id;
      });
    },
    // 6 点击确定进行角色的编辑，校验表单
    editRoles() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const {
            data: { meta }
          } = await this.$http.put(`roles/${this.editForm.id}`, {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          });
          if(meta.status !==200) return this.$message.error("编辑角色失败");
          
          this.$message.success("编辑角色成功");
          this.getData();
          this.editDialogFormVisible = false;
        }
      });
    },
    // 7 实现删除单个权限的功能
    delRights(row,rightId){
        this.$confirm("确定删除该权限吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(async () => {
              const {
                data: { data,meta }
              } = await this.$http.delete(`roles/${row.id}/rights/${rightId}`);
              // 失败情况
              if (meta.status !== 200) return this.$message.error("删除角色权限失败");
              // 成功情况,只刷新当前页面
              row.children = data;
              this.$message({
                type: "success",
                message: "删除权限成功!"
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除权限"
              });
            });
    },
    // 8 点击分配权限，显示树状对话框，渲染数据
    async openRightDialog(row){
        const {data:{data,meta}}= await this.$http(`rights/tree`);
        if(meta.status !==200) return this.$message.error('获取树状权限数据失败')
        this.rightsTreeForm = data;
        this.rightsRoleId=row.id;
        // 选中已有权限的效果,拿到第三级的权限id
        let arr=[];
        row.children.forEach(item=>{
            item.children.forEach(subitem=>{
                subitem.children.forEach(lastitem=>{
                    arr.push(lastitem.id);
                })
            })
        });
        this.checkedIdArr = arr;
        this.rightDialogFormVisible = true;
    },
    // 9 点击确定，完成分配权限的功能
    async disRights(){
        // 9.1获取全选的权限id
        const checkedArr = this.$refs.tree.getCheckedKeys();
        // 9.2获取半选的权限id
        const halfCheckedArr = this.$refs.tree.getHalfCheckedKeys();
        // 9.3合并
        const arr = [...checkedArr,...halfCheckedArr];
        // console.log(arr);
        const {data:{meta}}= await this.$http.post(`roles/${this.rightsRoleId}/rights`,{
            rids: arr.join(",")
        });
        if(meta.status !==200) return this.$http.error('角色分配权限失败');
        this.$message.success('角色分配权限成功');
        this.getData();
        this.rightDialogFormVisible=false;
    }
  }
};
